import React from 'react';
import { Layout as AntLayout, Button, Typography, Avatar, Dropdown, Space } from 'antd';
import { UserOutlined, LogoutOutlined, ArrowLeftOutlined, HomeOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { ROUTES } from '../constants/routes';

const { Header, Content } = AntLayout;
const { Title } = Typography;

interface LayoutProps {
  children: React.ReactNode;
  title?: string;
  showBackButton?: boolean;
}

const Layout: React.FC<LayoutProps> = ({ 
  children, 
  title = '医疗系统', 
  showBackButton = true 
}) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { user, logout } = useAuth();

  const handleBack = () => {
    // 如果有历史记录，则返回上一页
    if (window.history.length > 2) {
      navigate(-1);
    } else {
      // 否则根据用户角色返回仪表盘
      if (user?.role === 'doctor') {
        navigate(ROUTES.doctor.dashboard);
      } else if (user?.role === 'patient') {
        navigate(ROUTES.patient.dashboard);
      }
    }
  };

  const handleLogout = () => {
    logout();
    navigate(ROUTES.login);
  };

  const menuItems = [
    {
      key: '1',
      label: (
        <Button 
          type="link" 
          icon={<LogoutOutlined />} 
          onClick={handleLogout}
        >
          退出登录
        </Button>
      ),
    },
  ];

  return (
    <AntLayout className="layout" style={{ minHeight: '100vh' }}>
      <Header style={{ background: '#fff', padding: 0, paddingHorizontal: 24, display: 'flex', alignItems: 'center', justifyContent: 'space-between', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          {showBackButton && (
            <Button 
              type="text" 
              icon={<ArrowLeftOutlined />} 
              onClick={handleBack}
              title="返回"
            />
          )}
          <Button 
            type="text" 
            icon={<HomeOutlined />} 
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              console.log('首页按钮被点击，用户类型:', user?.type);
              if (user?.type === 'doctor') {
                navigate(ROUTES.doctor.dashboard);
              } else if (user?.type === 'patient') {
                navigate(ROUTES.patient.dashboard);
              } else {
                // 添加默认导航，确保无论如何都能导航
                navigate('/');
              }
            }}
            title="首页"
            style={{ cursor: 'pointer', zIndex: 10 }} // 确保按钮可点击并有足够的层级
          />
          <Title level={4} style={{ margin: 0, color: '#1890ff' }}>{title}</Title>
        </div>
        
        <Dropdown menu={{ items: menuItems }}>
          <Space>
            <span style={{ marginRight: 8 }}>{user?.name || '用户'}</span>
            <Avatar icon={<UserOutlined />} />
          </Space>
        </Dropdown>
      </Header>
      <Content style={{ margin: 24, padding: 24, background: '#fff', minHeight: 280, borderRadius: 8 }}>
        {children}
      </Content>
    </AntLayout>
  );
};

export default Layout;